package com.hardy.leetcode;

import java.util.Stack;

/**
 * 题目描述
 *
 * Given an absolute path for a file (Unix-style), simplify it. For example, path ="/home/",
 * =>"/home" path ="/a/./b/../../c/", =>"/c" click to show corner cases. Corner Cases:
 *
 * Did you consider the case where path ="/../"? In this case, you should return"/". Another corner
 * case is the path might contain multiple slashes'/'together, such as"/home//foo/". In this case,
 * you should ignore redundant slashes and return"/home/foo". User: Ruijie Date: 2016/9/21
 */
public class SimplifyPath {

    public static String simplifyPath(String path) {
        if(path==null||path.length()==0){
            return null;
        }
        String[] sAttr=path.split("/");
        Stack<String> stack=new Stack<String>();
        for(String s:sAttr){
           if(s.equals("")||s.equals(".")){
               continue;
           }else if(s.equals("..")){
               if(!stack.isEmpty()){
                   stack.pop();
               }
           }else{
               stack.push(s);
           }

        }
        if(stack.isEmpty()){
            return "/";
        }
        reverse(stack);
        StringBuffer sb=new StringBuffer();
        while(!stack.isEmpty()){
            String str="/"+stack.pop();
            sb.append(str);
        }
        return sb.toString();
    }

    public static void reverse(Stack<String> stack){
        if(stack.isEmpty()){
            return;
        }
        String s=getAndRemoveBottom(stack);
        reverse(stack);
        stack.push(s);
    }

    public static String getAndRemoveBottom(Stack<String> stack){
        String result=stack.pop();
        if(stack.isEmpty()){
            return result;
        }else{
            String bottom=getAndRemoveBottom(stack);
            stack.push(result);
            return bottom;
        }

    }
    public static void main(String[] args) {
        System.out.println(simplifyPath("/../"));
    }
    private static void printStack(Stack<String> stack){
        while(!stack.isEmpty()){
            System.out.print(stack.pop()+" ");
        }
    }
}
